/**
 * 订阅发布模式
 */
class EventEmitter {
  //用于存储事件及其处理函数
  events = {};
  //用于存储数据对象
  data = {};

  // 订阅事件
  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(listener);
  }

  // 取消订阅事件
  off(event, listener) {
    if (!this.events[event]) {
      return;
    }
    this.events[event] = this.events[event].filter(l => l !== listener);
  }

  // 发布事件
  emit(event, ...args) {
    if (!this.events[event]) {
      return;
    }
    this.events[event].forEach(listener => listener.apply(this, args));
  }

  setData(key, value) {
    this.data[key] = value;
  }

  getData(key, defaultValue?: any) {
    return this.data?.[key] ?? defaultValue
  }
}

export const emitter = new EventEmitter()